package ua.kharkov.knure.pereverziev.diploma.web.filter;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * Forwards to login page when the current session is invalidate.
 */
public class SecurityFilter implements Filter {

	private static final Logger log = Logger.getLogger(SecurityFilter.class);

	private static Set<String> permitedCommands = getPermitedCommands();

	public void destroy() {
		// do nothing
	}

	/**
	 * Forwards to login page when the current session is invalidate.
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		log.debug("Filter starts");

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;

		if (httpServletRequest.getSession().getAttribute("user") == null) {
			if (!permitedCommands.contains(httpServletRequest
					.getParameter("command"))) {
				log.error("Somebody tried to hack site");
				httpServletRequest
						.getRequestDispatcher(
								"/login.jsp?error=This option is available only for autorized users!")
						.forward(request, response);
				return;
			}
		}

		// otherwise go further
		chain.doFilter(request, response);
		log.debug("Filter finished");
	}

	public void init(FilterConfig fConfig) throws ServletException {
		// do nothing
	}

	private static Set<String> getPermitedCommands() {
		Set<String> commands = new HashSet<String>(25);
		commands.add("login");
		commands.add("logout");
		commands.add("registration");
		commands.add("password_recovery");
		commands.add("secure_goto");
		commands.add("changeLocale");
		commands.add("go_back");
		return commands;
	}

}
